package com.controller;

import java.util.Arrays;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.constant.AuthConstant;
import com.exception.ErrorCode.ChargingErrorCode;
import com.utils.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.domain.entity.ChongdianzhuangEntity;

import com.service.ChongdianzhuangService;
import com.utils.PageUtils;
import com.utils.R;

@RestController
@RequestMapping("/chongdianzhuang")
public class ChongdianzhuangController {
    @Autowired
    private ChongdianzhuangService chongdianzhuangService;

    @Autowired
    private RedisClient redisClient;


    /**
     * 管理员充电桩分页查询
     */
    @GetMapping("/page")
    public R page(@RequestParam int pageNum,@RequestParam int pageSize,ChongdianzhuangEntity chongdianzhuang){

		PageUtils page = chongdianzhuangService.queryPage(pageNum,pageSize,chongdianzhuang);
        return R.ok().put("data", page);
    }

    /**
     * 管理员充电桩详情
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){

        String json = redisClient.getString(AuthConstant.CHARGING_INFO_PREFIX + id);
        if (StringUtils.isNotEmpty(json)) {

            ChongdianzhuangEntity entity = JSONObject.parseObject(json, ChongdianzhuangEntity.class);
            return R.ok().put("data", entity);
        }

        ChongdianzhuangEntity entity = chongdianzhuangService.selectById(id);
        if (entity != null) {
            redisClient.setMinString(AuthConstant.CHARGING_INFO_PREFIX + id, JSONObject.toJSONString(entity),2000L);
        }

        return R.ok().put("data", entity);
    }


    /**
     * 管理员充电桩新增
     */
    @PostMapping("/save")
    public R save(@RequestBody ChongdianzhuangEntity chongdianzhuang){

        int count = chongdianzhuangService.selectCount(new Condition()
                .eq("dianzhuangbianhao", chongdianzhuang.getDianzhuangbianhao()));

        if (count > 0) {
            return R.error(ChargingErrorCode.CHARGING_ID_IS_EXIST.getMessage());
        }

        chongdianzhuang.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
        chongdianzhuangService.insert(chongdianzhuang);
        return R.ok();
    }

    /**
     * 管理员充电桩更新
     */
    @PostMapping("/update")
    public R update(@RequestBody ChongdianzhuangEntity chongdianzhuang){
        chongdianzhuangService.updateById(chongdianzhuang);
        return R.ok();
    }

    /**
     * 管理员充电桩删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        chongdianzhuangService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


}
